package com.wu.http.server;

import com.wu.util.TomcatUtil;
import com.wu.threadPool.Task;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

import static com.wu.constant.Constant.*;

public class TaskService implements Task {
    private final Socket socket;
    private final InputStream iis;
    private final OutputStream oos;
    private boolean flag;
    private static Map<String, String> MAPPING_MAP;

    public TaskService(Socket socket) {
        MAPPING_MAP = Main.getMappingMap();
        this.socket = socket;
        try {
            this.iis = this.socket.getInputStream();
            this.oos = this.socket.getOutputStream();
            flag = true;
        } catch (IOException e) {
            logger.error(" failed to get stream  ", e);
            flag = false;
            throw new RuntimeException(e);
        }
    }

    /**
     * HTTP协议是一次请求和响应.  http是无状态 一次请求和响应就会断开联接..
     */
    @Override
    public Object doTask() {
        if (flag) {
            //包装一个HttpServletRequest对象
            MyHttpServletRequest request = new MyHttpServletRequest(this.iis);
            //包装一个HttpServletResponse对象
            MyHttpServletResponse response = new MyHttpServletResponse(request, this.oos);
            //判断是静态资源还是动态资源
            Processor processor;
            boolean flag = true;
            String fileExtension;
            fileExtension = TomcatUtil.getFileExtension(request.getRequestURI());
            if (fileExtension.trim().length() > 0) {
                for (Map.Entry<String, String> entry : MAPPING_MAP.entrySet()) {
                    if (entry.getKey().equalsIgnoreCase(fileExtension)) {
                        flag = false;
                        break;
                    }
                }
            }
            if (flag) {
                processor = new DynamicProcessor();
            } else {
                processor = new StaticProcessor();
            }
            processor.process(request, response);
        }
        try {
            this.socket.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(" failed to close connection to client  ", e);
        }
        return null;
    }
}
